package com.rq.shuduapp;

import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class BASE {
    public static int commonLayoutId;
    public static int statusColorId = Color.WHITE;
    private static Context ctx;
    private static String mSessionId;
    private static int mNetErrorToast;
    private static String ROOT_DIR;
    private static String BASE_DIR;
    public static int PAGE_SIZE_START = 1;

    public static int TYPE = 1;

    private static int needLockScreenOrientation = 0;//0-自感应 1-竖屏固定 2-横屏固定

    public static int getLockScreenOrientation() {
        return needLockScreenOrientation;
    }

    public static void setLockScreenOrientation(int orientation) {
        BASE.needLockScreenOrientation = orientation;
    }

//    public static void setNeedLockOrientation(boolean needLockOrientation) {
//        if (needLockOrientation) {
//            if (AppUtils.isMobilePhone()) {
//                needLockScreenOrientation = 1;
//            } else {
//                needLockScreenOrientation = 2;
//            }
//        }
//    }

    public static void setType(int type) {
        TYPE = type;
    }

    public static boolean isZuYu() {
        return TYPE == 0;
    }

    private static Set<String> url = new HashSet<>();

    private static Map<String, String> headMap = new HashMap<>();

    public static void setHead(Map<String, String> headers) {
        headMap.clear();
        headMap.putAll(headers);
    }

    public static Map<String, String> getHead() {
        return headMap;
    }

    public static void addUrl(String... baseUrl) {
        BASE.url.addAll(Arrays.asList(baseUrl));
    }

    private static String downUrl = "";

    public static String getDownloadUrl() {
        return downUrl;
    }

    public static void setDownloadUrl(String url) {
        String head = url.substring(0, url.indexOf("//") + 2);
        String u = url.substring(url.indexOf("//") + 2);
        downUrl = head + u.substring(0, u.indexOf("/"));
        LOG.e("BASE", "setDownloadUrl.downUrl:" + downUrl);
    }

    public static Context getCxt() {
        return ctx;
    }

    //没有以 "/" 结尾
    public static String getBaseDir() {
        return BASE_DIR;
    }

    public static void setCommonLayout(int layout, int color) {
        commonLayoutId = layout;
        statusColorId = color;
    }

    public static void setSessionId(String id) {
        LOG.e("BASE", "setSessionId:-> " + mSessionId);
        mSessionId = id;
    }

    public static String getSessionId() {
        LOG.e("BASE", "getSessionId:-> " + mSessionId);
        return mSessionId;
    }

    public static String getString(int res) {//字模块方法
        return getCxt().getString(res);
    }

    public static void init(Application context, String baseDirName) {
        ctx = context;
        SPUtil.init(context);
        //    SPUtil.setCxt(context);
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            LOG.e("BASE", "init.128:");
            ROOT_DIR = Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            LOG.e("BASE", "init.131:");
            ROOT_DIR = System.getenv("EXTERNAL_STORAGE");
        }
        BASE_DIR = ROOT_DIR + "/" + baseDirName;
        refuseBase();
    }

    public static void refuseBase() {
        File base = new File(BASE_DIR);
        if (!base.exists()) {
            base.mkdirs();
            LOG.e("BASE", "refuseBase.66:");
        }
        LOG.e("BASE", "refuseBase.70:");
    }

    public static boolean hasSDPermission() {
        return new File(BASE_DIR).exists();
    }


    public static void setNetErrorToast(int res) {
        mNetErrorToast = res;
    }

    public static int getNetErrorToast() {
        return mNetErrorToast;
    }

    /**
     * @return getUseFrom 所在方法的上层调用处
     */
    public static String getUseFrom() {
        StackTraceElement[] stacks = new Exception().getStackTrace();
        if (stacks != null) {
            try {
                String classname = stacks[2].getFileName(); //获取调用者的类名
                String method_name = stacks[2].getMethodName(); //获取调用者的方法名
                int line = stacks[2].getLineNumber(); //获取调用者的方法名
                return classname + "[" + method_name + "]." + line;
            } catch (Exception e) {
            }
        }
        return "";
    }

    public static boolean showLog() {
        return BuildConfig.DEBUG;
    }

    public static boolean isDebug() {
        return BuildConfig.DEBUG | isRQ();
    }

    public static boolean isRQ() {//调试版本，跳过某些判断
        return new File(ROOT_DIR + "/rq").exists();
    }

    //    implementation 'com.tencent.tbs.tbssdk:sdk:43697'
    public static void initQQWeb(Context context) {
//    QbSdk.initX5Environment(context, new QbSdk.PreInitCallback() {
//      @Override
//      public void onCoreInitFinished() {
//        LOG.e("WelcomeController", "initQQWeb:136");
//        //x5内核初始化完成回调接口，此接口回调并表示已经加载起来了x5，有可能特殊情况下x5内核加载失败，切换到系统内核。
//      }
//
//      @Override
//      public void onViewInitFinished(boolean b) {
//        //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
//        Log.e("WelcomeController", "initQQWeb.加载内核是否成功:" + b);
//      }
//    });
    }
//
//    private static Class<? extends BaseController> LoginHelper;
//
//    public static <C extends BaseController> void setLoginHelper(Class<C> welcomeClass) {
//        LoginHelper = welcomeClass;
//    }
//
//    public static Class<? extends BaseController> getLoginHelper() {
//        return LoginHelper;
//    }
//
//    private static Class<?> welcomeClazz;
//
//    public static <C extends WelcomeImpl> void setQuickUi(Class<C> welcomeClass) {
//        welcomeClazz = welcomeClass;
//    }
//
//    public static Class<?> getWelcomeClazz() {
//        return welcomeClazz;
//    }
//
//    public static int getLayoutId(int hasScrollView, boolean isFragment) {
//        if (commonLayoutId == 0) {
//            LOG.d("BASE", "getLayoutId.hasScrollView:" + hasScrollView);
//            LOG.d("BASE", "getLayoutId.isFragment:" + isFragment);
//            if (hasScrollView == 1) {
//                return isFragment ? R.layout.fragment_base_nssc : R.layout.activity_base_nssc;
//            } else if (hasScrollView == 2) {
//                return isFragment ? R.layout.fragment_base_no_scroller : R.layout.activity_base_no_scroller;
//            } else {
//                return isFragment ? R.layout.fragment_base : R.layout.activity_base;
//            }
//        }
//        return commonLayoutId;
//    }
//
//    static Class<? extends BaseController> mainClass;
//
//    public static void setMainClass(Class<? extends BaseController> calzz) {
//        BASE.mainClass = calzz;
//    }
//
//
//    public static void toMain(Class<? extends BaseController> calzz) {
////    LOG.e("BASE", "toMain.243:" + mainClass.getSimpleName());
////    //    if (isRQ()) {
////    //      loginController.open(mainClass);
////    //    } else {
////    loginController.skip(mainClass);
//        //    }
//    }

    public static boolean isChangeUrl = false;
    private static String BCS_url;
    private static String SYS_url;

    public static String getSysUrl() {
        return SYS_url;
    }
    public static String getBcsUrl() {
        return BCS_url;
    }

    public static String dealUrl(String url) {
        String bcsPath = ROOT_DIR + "/rq/bcs.txt";
        String sysPath = ROOT_DIR + "/rq/sys.txt";
        try {
            if (new File(bcsPath).exists()) {
                BCS_url = readTxt(bcsPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (new File(sysPath).exists()) {
                SYS_url = readTxt(sysPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (String s : BASE.url) {
            if (url != null && BCS_url != null && url.contains(s)) {
                url = url.replace(s, BCS_url);
                isChangeUrl = true;
                return url;
            } else if (url != null && SYS_url != null && url.contains(s)) {
                url = url.replace(s, SYS_url);
                isChangeUrl = true;
                return url;
            }
        }
        return url;
    }

    public static String readTxt(String path) {
        String str = "";
        try {
            File urlFile = new File(path);
            InputStreamReader isr = new InputStreamReader(new FileInputStream(urlFile), "UTF-8");
            BufferedReader br = new BufferedReader(isr);

            String mimeTypeLine = null;
            while ((mimeTypeLine = br.readLine()) != null) {
                str = str + mimeTypeLine;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

}
